import Vue from 'vue';
import { PopupManager } from '@/vuego/utils/popup';
import { isVNode } from '@/vuego/utils/vdom';
import VNotification from './v-notification';

const NotificationConstructor = Vue.extend(VNotification);

let instance;
let seed = 1;

const instances = [];

const Notification = (options) => {
  if (Vue.prototype.$isServer) return false;
  options = options || {};
  const userOnClose = options.onClose;
  const id = `notification_${seed += 1}`;
  const position = options.position || 'top-right';

  options.onClose = () => {
    Notification.close(id, userOnClose);
  };

  instance = new NotificationConstructor({
    data: options,
  });

  if (isVNode(options.message)) {
    instance.$slots.default = [options.message];
    options.message = '';
  }
  instance.id = id;
  instance.vm = instance.$mount();
  document.body.appendChild(instance.vm.$el);
  instance.vm.visible = true;
  instance.dom = instance.vm.$el;
  instance.dom.style.zIndex = PopupManager.nextZIndex();

  let verticalOffset = options.offset || 0;
  instances.filter(item => item.position === position).forEach((item) => {
    verticalOffset += item.$el.offsetHeight + 16;
  });
  verticalOffset += 16;
  instance.verticalOffset = verticalOffset;
  instances.push(instance);
  return instance.vm;
};

['success', 'warning', 'info', 'error'].forEach((type) => {
  Notification[type] = (options) => {
    if (typeof options === 'string' || isVNode(options)) {
      options = {
        message: options,
      };
    }
    options.type = type;
    return Notification(options);
  };
});

Notification.close = (id, userOnClose) => {
  let index = -1;
  const len = instances.length;
  instance = instances.filter((inst, i) => {
    if (inst.id === id) {
      index = i;
      return true;
    }
    return false;
  })[0];
  if (!instance) return;

  if (typeof userOnClose === 'function') {
    userOnClose(instance);
  }
  instances.splice(index, 1);

  if (len <= 1) return;
  const position = instance.position;
  const removedHeight = instance.dom.offsetHeight;
  for (let i = index; i < len - 1; i += 1) {
    if (instances[i].position === position) {
      /* eslint no-mixed-operators: 0 */
      instances[i].dom.style[instance.verticalProperty] = `${parseInt(instances[i].dom.style[instance.verticalProperty], 10) - removedHeight - 16}px`;
    }
  }
};

export default Notification;
